﻿using Furion.Authorization;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using System.Threading.Tasks;
using Cool.Core.Managers;
using Microsoft.Extensions.DependencyInjection;

namespace Cool.Web.Core
{
    public class JwtHandler : AppAuthorizeHandler
    {
        public override Task<bool> PipelineAsync(AuthorizationHandlerContext context, DefaultHttpContext httpContext)
        {
            // 这里写您的授权判断逻辑，授权通过返回 true，否则返回 false

            return CheckAuthorzieAsync(httpContext);
        }

        /// <summary>
        /// 检查权限
        /// </summary>
        /// <param name="httpContext"></param>
        /// <returns></returns>
        private static Task<bool> CheckAuthorzieAsync(DefaultHttpContext httpContext)
        {
            // 获取权限特性
            var securityDefineAttribute = httpContext.GetMetadata<SecurityDefineAttribute>();
            if (securityDefineAttribute == null) return Task.FromResult(true);

            // 解析服务
            var userManager = httpContext.RequestServices.GetService<IUserManager>();
            var securities = userManager.GetSecuritiesAsync(userManager.UserId);
            // 检查授权
            return Task.FromResult(securities.Contains(securityDefineAttribute.ResourceId));
        }
    }
}